package com.baizhi.springboot.controller;

import com.baizhi.springboot.entity.Audio;
import com.baizhi.springboot.service.AudioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

@Controller
public class AudioController {
    @Autowired
    private AudioService audioService;
    private Integer i=1;

    @RequestMapping("/selectAudioByPage")
    @ResponseBody
    public Map selectAudioByPage(Integer page, Integer limit,Integer albumId) {
        return audioService.selectAudioByPage(page,limit,albumId);
    }
    @RequestMapping("/uploadAudio")
    @ResponseBody
    public Map  uploadAudio(MultipartFile file, HttpServletRequest request) throws IOException {
        //String realPath = request.getServletContext().getRealPath("/image");
        file.transferTo(new File("D:/uploadFile/"+file.getOriginalFilename()));
        String audioUrl=file.getOriginalFilename();
        /*float num =(float)member/denominator;
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(num)*/
        float size = (float)file.getSize()/1024/1024;
        DecimalFormat df = new DecimalFormat("0.0");
        String format = df.format(size);
        //System.out.println(audioUrl);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("audioUrl",audioUrl);
        map.put("audioSize",format+"M");
        return map;
    }
    @RequestMapping("/insertAudio")
    @ResponseBody
    public Map  insertAudio(Audio audio) throws IOException {
        HashMap<Object, Object> map = new HashMap<>();
        audio.setAudioOrder(i);
        i++;
        try {
            audioService.insertAudio(audio);
            map.put("isAdd", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isAdd", false);
        }
        return map;
    }
    @RequestMapping("/deleteAudio")
    @ResponseBody
    public Map  deleteAudio(Integer id){
        HashMap<Object, Object> map = new HashMap<>();

        try {
            audioService.deleteAudio(id);
            map.put("isDelete", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isDelete", false);
        }
        return map;
    }
}
